//
//  LoginViewController.m
//  wanzhaoIM
//
//  Created by liuyuantao on 15/4/7.
//  Copyright (c) 2015年 liuyuantao. All rights reserved.
//  Created by LIXU

#import "LoginViewController.h"
#import "WZRootViewController.h"
#import "EFengAndEtongRootController.h"
#import "EFRootViewController.h"
#import "MicroDef.h"
#import "CXmppMgr.h"
#import "AFNetworking.h"
#import "FMDB.h"
#import "TableViewWithBlock.h"
#import "SelectionCell.h"
#import "UIUtil.h"
#import "CAccountModel.h"
#import "CAccountMgr.h"
#import "JKAlertDialog.h"
#import "CCurrentAccountMgr.h"
#import "PersonalVersion.h"
#import "CServerSettingMgr.h"
#import "CServerSettingModel.h"
#import "CXmppRequestMgr.h"
#import "CFolderMgr.h"
#import "CContactMgr.h"
#import "CContactMgr.h"
#import "NSArray+PinYin.h"
#import "NSString+MyString.h"
#import "CommonVersion.h"
#import "CContactModel.h"
#import "CAttentionMgr.h"
#import "CMineAttentionContact.h"
#import "GesturePasswordController.h"
#import "UIImageView+WebCache.h"

#define KVERIFYTIMES 3//3次以后 出现校验吗

@interface LoginViewController()<UITextFieldDelegate, SectionDel_Delegate,UIAlertViewDelegate>
{
    NSOperationQueue *_queen;
    BOOL isUseverifyCode;
    BOOL isOpened;
    
    BOOL _keyboardIsShow;
    UITapGestureRecognizer *_tapGestureRecognizer;
}
@property(nonatomic, strong)UIImageView *logoView;
@property(nonatomic, strong)UITextField *userTF;
@property(nonatomic, strong)UIImageView *userImageView;
@property(nonatomic, strong)UITextField *passwordTF;
@property(nonatomic, strong)UIImageView *passwordImageView;
@property(nonatomic, strong)UIButton *loginBtn;
@property(nonatomic, strong)UIButton *serverConfigBtn;
@property(nonatomic, strong)UITextField *verifycodeTF;
@property(nonatomic, strong)UILabel *verifyLabel;
@property(nonatomic, strong)NSString *verifyCode;
@property(nonatomic, strong)UIButton *verifyRefreshBtn;
@property(nonatomic, strong)UIButton *historyUser;
@property(nonatomic, strong)UIButton *settingNet;

@property (nonatomic, strong) UIImageView *passwordBackView;

@property(nonatomic, strong)UIImageView *errIconImageView;
@property(nonatomic, strong)UILabel *errMsgLabel;
@property(nonatomic, strong)UIScrollView *scrollView;

@property (nonatomic, strong) CAccountModel *account;
@property (nonatomic, strong) NSTimer *timer;
@property FMDatabaseQueue *fmdbQueue;

StrongProperty NSArray *userList;
@end


#define KLOGINBASETAG 1000


#define KUSERNAMETAG (KLOGINBASETAG+1)
#define KPASSWORDTAG (KLOGINBASETAG+2)
#define KverifyCODETAG (KLOGINBASETAG+3)
#define IOS8 ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0 )



@implementation LoginViewController
@synthesize NopassWord;


-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:K_XMPPLOGINRESULT object:nil];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginResult:) name:K_XMPPLOGINRESULT object:nil];

    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

     self.account = [[CFolderMgr shareInstance].accMgr getRecentlyLoginAccount];
    
    _keyboardIsShow = NO;
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor clearColor];
    UIView *backgroundImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"loginBackground"]];
    backgroundImageView.frame = self.view.bounds;
    [self.view addSubview:backgroundImageView];
     _queen = [[NSOperationQueue alloc] init];
    CGFloat rate = 1.0f;
    CGFloat fontSize = 15.0f;
    if(HARDWARE_SCREEN_HEIGHT >= 736)
    {
//        rate = 1.30f;
        fontSize = 23.0f;
    }
//    [self.navigationItem setNewTitle:@"登陆"];
//    [self.navigationController.navigationBar setBarTintColor:[UIColor lightGrayColor]];
    
//    UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:self.view.frame];
    _scrollView= [[UIScrollView alloc] init];
    _scrollView.frame = self.view.bounds;
    _scrollView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_scrollView];
    
    
//    UIView *superview = self.view;
    UIImageView *logoBackgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"logoBackgroundImage"]];
    logoBackgroundView.frame = CGRectMake((HARDWARE_SCREEN_WIDTH - logoBackgroundView.image.size.width) / 2.0 , 95.0f, logoBackgroundView.image.size.width, logoBackgroundView.image.size.height);
//    [self.view addSubview:logoBackgroundView];
    [_scrollView addSubview:logoBackgroundView];
    
    
    
    
    _logoView = [[UIImageView alloc] init];
    _logoView.layer.cornerRadius = 42.5f;
    _logoView.layer.masksToBounds = YES;
    _logoView.layer.borderWidth = 3.0f;
    _logoView.layer.borderColor = [UIColor whiteColor].CGColor;
    _logoView.image = [UIImage imageNamed:@"defaultHeaderImage"];
    
    _logoView.frame = CGRectMake(0, 0, _logoView.image.size.width, _logoView.image.size.height);
    _logoView.center = logoBackgroundView.center;
//    _logoView.image = [_logoView sd_setImageWithURL:[NSURL URLWithString:[[CXmppRequestMgr shareInstance] DownHeadFileWithContact:[]] placeholderImage:<#(UIImage *)#>]
    [_logoView setBackgroundColor:[UIColor clearColor]];
//    [self.view addSubview:_logoView];
    [_scrollView addSubview:_logoView];
   
    
    UIImageView *userBackView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"userBackgroundImage"]];
    userBackView.frame = CGRectMake(15.0f, 215.0f, HARDWARE_SCREEN_WIDTH - 30.0f, 45.0f);
//    [userBackView setBackgroundColor: RGBCOLOR(0xff, 0xff, 0xff)];
//    userBackView.layer.borderWidth = 0.5;
//    userBackView.layer.borderColor = RGBCOLOR(0xc4, 0xc5, 0xc5).CGColor;
    userBackView.userInteractionEnabled = YES;
//    [self.view addSubview:userBackView];
    [_scrollView addSubview:userBackView];
    
    
    
    _userImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"userLogoImage"]];
    [userBackView addSubview:_userImageView];
    _userImageView.frame = CGRectMake(10.0f, (45.0f - _userImageView.image.size.height) / 2.0f, _userImageView.image.size.width, _userImageView.image.size.height);
    
    _historyUser = [[UIButton alloc] init];
    _historyUser.frame = CGRectMake(userBackView.frame.size.width - 33.0f, 0, 33.0f, 45.0f);
    [_historyUser setBackgroundColor:[UIColor clearColor]];
    [_historyUser setImage:[UIImage imageNamed:@"userNameListImg"] forState:UIControlStateNormal];
    [_historyUser setImage:[UIImage imageNamed:@"userNameListImg"] forState:UIControlStateSelected];
    [_historyUser addTarget:self action:@selector(changeOpenStatus:) forControlEvents:UIControlEventTouchUpInside];
    [userBackView addSubview:_historyUser];
    
    
    _userTF = [[UITextField alloc] init];
    _userTF.frame = CGRectMake(CGRectGetMaxX(_userImageView.frame) + 10.0f, 0, _historyUser.frame.origin.x - CGRectGetMaxX(_userImageView.frame) - 10.0f , 45.0f);
    _userTF.placeholder = @"请输入用户名";
    _userTF.delegate = self;
    _userTF.keyboardType = UIKeyboardTypeASCIICapable;
    _userTF.autocorrectionType = UITextAutocorrectionTypeNo;
    _userTF.backgroundColor = [UIColor clearColor];
    [_userTF setBorderStyle:UITextBorderStyleNone];
    _userTF.clearButtonMode = UITextFieldViewModeWhileEditing;
    [_userTF setTextAlignment:NSTextAlignmentLeft];
    [_userTF setFont:[UIFont systemFontOfSize:18*rate]];
    _userTF.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    _userTF.clipsToBounds = YES;
    _userTF.delegate = self;
    _userTF.tag = KUSERNAMETAG;
    [userBackView addSubview:_userTF];
    [_userTF addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    
    UIImageView *passwordBackView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"passwordBackgroundImage"]];
    self.passwordBackView = passwordBackView;
    passwordBackView.frame = CGRectMake(15.0f, CGRectGetMaxY(userBackView.frame), HARDWARE_SCREEN_WIDTH - 30.0f, 45.0f);
    //passwordBackgroundImage
//    [passwordBackView setBackgroundColor: RGBCOLOR(0xff, 0xff, 0xff)];
//    passwordBackView.layer.borderWidth = 0.5;
//    passwordBackView.layer.borderColor = RGBCOLOR(0xc4, 0xc5, 0xc5).CGColor;
    passwordBackView.userInteractionEnabled = YES;
//    [self.view addSubview:passwordBackView];
    [_scrollView addSubview:passwordBackView];
    
    
    _passwordImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"passwordLogoImage"]];
    _passwordImageView.frame = CGRectMake(10.0f, (45.0f - _passwordImageView.image.size.height) / 2.0f, _passwordImageView.image.size.width, _passwordImageView.image.size.height);
    [passwordBackView addSubview:_passwordImageView];

    
    _passwordTF = [[UITextField alloc] init];
    _passwordTF.frame = CGRectMake(CGRectGetMaxX(_passwordImageView.frame) + 10.0f, 0, passwordBackView.frame.size.width - CGRectGetMaxX(_passwordImageView.frame) - 10.0f, 45.0f);
    _passwordTF.placeholder = @"请输入密码";
    _passwordTF.backgroundColor = [UIColor clearColor];
    _passwordTF.secureTextEntry = YES;
    _passwordTF.keyboardType = UIKeyboardTypeASCIICapable;
    _passwordTF.delegate = self;
    _passwordTF.textAlignment = NSTextAlignmentLeft;
    _passwordTF.tag = KPASSWORDTAG;
    [_passwordTF setFont:[UIFont systemFontOfSize:18*rate]];
    [passwordBackView addSubview:_passwordTF];
    
    
    _loginBtn = [[UIButton alloc] init];
    _loginBtn.frame = CGRectMake(15.0f, CGRectGetMaxY(passwordBackView.frame) + 30.0f, HARDWARE_SCREEN_WIDTH - 30.0f, 45.0f);
    [_loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    [_loginBtn setTitleColor:RGBCOLOR(0xf8, 0xf8, 0xf8) forState:UIControlStateNormal];
    [_loginBtn setBackgroundImage:[UIImage imageNamed:@"loginBtnNormal"] forState:UIControlStateNormal];
    [_loginBtn setBackgroundImage:[UIImage imageNamed:@"loginBtnHighLight"] forState:UIControlStateHighlighted];
    [_loginBtn addTarget:self action:@selector(loginAction:) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:_loginBtn];
    [_scrollView addSubview:_loginBtn];
    
   

    _verifycodeTF = [[UITextField alloc] init];
    _verifycodeTF.frame = CGRectMake(15.0f, CGRectGetMaxY(passwordBackView.frame) + 13.0f, 90.0f, 35.0f);
    _verifycodeTF.textAlignment = NSTextAlignmentCenter;
    [_verifycodeTF setBackgroundColor:RGBCOLOR(0xff, 0xff, 0xff)];
    _verifycodeTF.delegate = self;
    _verifycodeTF.tag = KverifyCODETAG;
    _verifycodeTF.layer.borderColor = RGBCOLOR(0xc4, 0xc5, 0xc5).CGColor;
    _verifycodeTF.layer.borderWidth = 0.5;
    _verifycodeTF.layer.cornerRadius = 5.0f/2;
//    [self.view addSubview:_verifycodeTF];
    _verifycodeTF.keyboardType = UIKeyboardTypeEmailAddress;
    [_scrollView addSubview:_verifycodeTF];

    _verifyLabel = [[UILabel alloc] init];
    _verifyLabel.frame = CGRectMake(CGRectGetMaxX(_verifycodeTF.frame) + 10.0f, CGRectGetMaxY(passwordBackView.frame) + 13.0f, 65.0f, 35.0f);
    [_verifyLabel setBackgroundColor:RGBCOLOR(0xff, 0xff, 0xff)];
    _verifyLabel.textColor = RGBCOLOR(0x21, 0x5d, 0x89);
    [_verifyLabel setTextAlignment:NSTextAlignmentCenter];
    [_verifyLabel setFont:[UIFont systemFontOfSize:14*rate]];
//    [self.view addSubview:_verifyLabel];
    [_scrollView addSubview:_verifyLabel];
    
    _verifyRefreshBtn = [[UIButton alloc] init];
    [_verifyRefreshBtn setImage:[UIImage imageNamed:@"verifyBtnImage"] forState:UIControlStateNormal];
    _verifyRefreshBtn.frame = CGRectMake(CGRectGetMaxX(_verifyLabel.frame) + 10.0f, CGRectGetMaxY(passwordBackView.frame) + 13.0f, _verifyRefreshBtn.currentImage.size.width, 35.0f);
    [_verifyRefreshBtn addTarget:self action:@selector(updateVerifyCode) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:_verifyRefreshBtn];
    [_scrollView addSubview:_verifyRefreshBtn];
    
    _errIconImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"loginErrorImage"]];
    _errIconImageView.backgroundColor = [UIColor clearColor];
//    [self.view addSubview:_errIconImageView];
    [_scrollView addSubview:_errIconImageView];
    _errIconImageView.frame = CGRectMake(15.0f, CGRectGetMaxY(_loginBtn.frame) + 17.5f, _errIconImageView.image.size.width, _errIconImageView.image.size.height);
    
    _errMsgLabel = [[UILabel alloc] init];
    _errMsgLabel.frame = CGRectMake(CGRectGetMaxX(_errIconImageView.frame) + 6.0f, CGRectGetMaxY(_loginBtn.frame) + 17.5f,  159.0f, _errIconImageView.image.size.height);
    _errMsgLabel.backgroundColor = [UIColor clearColor];
    [_errMsgLabel setTextColor:RGBCOLOR(0xf4, 0x62, 0x0b)];
    [_errMsgLabel setFont:[UIFont systemFontOfSize:14*rate]];
//    [self.view addSubview:_errMsgLabel];
    [_scrollView addSubview:_errMsgLabel];
    
    
    
    _settingNet =[[UIButton alloc]init];
    _settingNet.frame = CGRectMake(CGRectGetMaxX(_errMsgLabel.frame), CGRectGetMaxY(_loginBtn.frame) + 17.5f, 60.0f, _errIconImageView.image.size.height);
    _settingNet.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [_settingNet addTarget:self action:@selector(clickSetting) forControlEvents:UIControlEventTouchUpInside];
    if (IOS8) {
        NSMutableAttributedString *str2 = [[NSMutableAttributedString alloc] initWithString:@"网络设置"];
        NSRange strRange = {0,[str2 length]};
        [str2 addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:strRange];
        _settingNet.titleLabel.textColor=[UIColor blueColor];
        [_settingNet.titleLabel setFont:[UIFont systemFontOfSize:14*rate]];
        [_settingNet setAttributedTitle:str2 forState:UIControlStateNormal];
    } else{
        NSString *str2 =@"网络设置";
        [_settingNet.titleLabel setFont:[UIFont systemFontOfSize:14*rate]];
        [_settingNet setTitleColor:RGBCOLOR(0xf4, 0x62, 0x0b) forState:UIControlStateNormal];
        [_settingNet setTitle:str2 forState:UIControlStateNormal];
        [_settingNet setEnabled:NO];
    }
    [_scrollView addSubview:_settingNet];

    
    _tb = [[TableViewWithBlock alloc] init];
    _tb.frame = CGRectMake(15.0f, CGRectGetMaxY(userBackView.frame) + 0.5f, HARDWARE_SCREEN_WIDTH - 30.0f, 0);
    [_tb setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    _tb.layer.borderColor  = RGBCOLOR(0xc4, 0xc5, 0xc5).CGColor;
//    _tb.layer.borderColor = [UIColor redColor].CGColor;
    _tb.layer.borderWidth = 0.5;
    _tb.layer.cornerRadius = 5.0f/2;
  
    [_scrollView addSubview:_tb];
    
    [self updateUserList];
    isOpened=NO;

    
    __weak LoginViewController *weakSelf = self;
    __weak TableViewWithBlock *weakTb = _tb;
    
    [_tb initTableViewDataSourceAndDelegate:^NSInteger(UITableView *tableView, NSInteger section) {
        return weakSelf.userList.count;
    } setCellForIndexPathBlock:^UITableViewCell *(UITableView *tableView, NSIndexPath *indexPath) {
        SelectionCell *cell=[tableView dequeueReusableCellWithIdentifier:@"SelectionCell"];
        if (!cell) {
            cell=[[[NSBundle mainBundle]loadNibNamed:@"SelectionCell" owner:self options:nil]objectAtIndex:0];
            //            [cell setSelectionStyle:UITableViewCellSelectionStyleGray];
        }
        cell.delDelegate = self;
        cell.account = weakSelf.userList[indexPath.row];
        return cell;
    } setDidSelectRowBlock:^(UITableView *tableView, NSIndexPath *indexPath) {
        CAccountModel *curaccount = [_userList objectAtIndex:indexPath.row];
        [weakSelf.logoView sd_setImageWithURL:[NSURL URLWithString:[[CXmppRequestMgr shareInstance] DownHeadFileWithContact:curaccount.userId]] placeholderImage:[UIImage imageNamed:@"defaultHeaderImage"]];

        weakSelf.userTF.text = curaccount.loginName;
        //bug 9459 fixed by lixu
//        weakSelf.passwordTF.text = curaccount.passWord;
        
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        [weakSelf changeOpenStatus:nil];
    } commitEditingBlock:^(UITableView *tableView, UITableViewCellEditingStyle editingStyle, NSIndexPath *indexPath) {
        if (editingStyle == UITableViewCellEditingStyleDelete) {
            
            CAccountModel *acc = weakSelf.userList[indexPath.row];
            weakSelf.passwordTF.text = @"";
            if(acc != nil)
            {
                acc.isShowInList = NO;
                [[CFolderMgr shareInstance].accMgr updateAccount:acc];
                weakSelf.userList = [[CFolderMgr shareInstance].accMgr getAccountNameList];
                
                float tbHeight;
                if (weakSelf.userList.count >= 2) {
                    tbHeight = 88.0f;
                } else {
                    tbHeight = weakSelf.userList.count * 44.0f;
                }
                
                CGRect frame= weakTb.frame;
                
                frame.size.height=tbHeight;
                [weakTb setFrame:frame];
                
                
                [weakTb reloadData];
                
            }
        }

    }];
    
    
    [self setverifyStatus:NO];
    [self setErrStatus:NO errorMsg:nil];
    
//    self.fmdbQueue = [FMDatabaseQueue databaseQueueWithPath:self.databasePath];
    _scrollView.scrollEnabled = YES;
    _scrollView.showsVerticalScrollIndicator = YES;
    [_scrollView setContentSize:CGSizeMake(self.view.frame.size.width, 2000)];
    
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyboardHideAction:)];
//    设置成NO表示当前控件响应后会传播到其他控件上，默认为YES。
    tapGestureRecognizer.cancelsTouchesInView = NO;
    //将触摸事件添加到当前view
    [self.view addGestureRecognizer:tapGestureRecognizer];
    _tapGestureRecognizer = tapGestureRecognizer;

    
       _errTimes = 0;
}


-(void)updateUserList
{
    _userList = [[CFolderMgr shareInstance].accMgr getAccountNameList];

}
//好牛逼的bug 被李旭改了。。。
- (void) textFieldDidChange:(UITextField *) TextField
{
    isOpened = YES;
    NSString *text = [TextField.text stringByReplacingOccurrencesOfString:@"@" withString:@"_"];
    [self updateUserList];
    if (TextField.text.length>0) {
        NSMutableArray *accountArray = [_userList mutableCopy];
        for (CAccountModel *model in _userList) {
            NSRange range = [[model.userName lowercaseString] rangeOfString:[text lowercaseString]];
            if (range.location == NSNotFound) {
                [accountArray removeObject:model];
            }
        }
        if (accountArray.count == 0) {
            [UIView animateWithDuration:0.3 animations:^{
                UIImage *closeImage=[UIImage imageNamed:@"userNameListImg"];
                [_historyUser setImage:closeImage forState:UIControlStateNormal];
                
                CGRect frame=_tb.frame;
                
                frame.size.height=0;
                [_tb setFrame:frame];
                
            } completion:^(BOOL finished){
                
                isOpened=NO;
            }];

        }
        else
        {
            __block float tbHeight;
            tbHeight = accountArray.count * 44.0f;
            if (accountArray.count>5) {
                tbHeight = 5 * 44.0f;
                
            }
            [UIView animateWithDuration:0.3 animations:^{
                UIImage *openImage=[UIImage imageNamed:@"userNameListImg"];
                [_historyUser setImage:openImage forState:UIControlStateNormal];
                
                CGRect frame=_tb.frame;
                
                frame.size.height=tbHeight;
                [_tb setFrame:frame];
            } completion:^(BOOL finished){
                isOpened=YES;
            }];

        }
        _userList = [accountArray copy];
    }
    else
    {
        [UIView animateWithDuration:0.3 animations:^{
            UIImage *closeImage=[UIImage imageNamed:@"userNameListImg"];
            [_historyUser setImage:closeImage forState:UIControlStateNormal];
            
            CGRect frame=_tb.frame;
            
            frame.size.height=0;
            [_tb setFrame:frame];
            
        } completion:^(BOOL finished){
            
            isOpened=NO;
        }];

    }
     [_tb reloadData];
}


-(void)keyboardHideAction:(UITapGestureRecognizer*)tap{
   
    if (CGRectContainsPoint(CGRectMake(_verifyRefreshBtn.frame.origin.x, _verifyRefreshBtn.frame.origin.y, 40, 40), [tap locationInView:self.scrollView]) || CGRectContainsPoint(_userTF.frame, [tap locationInView:_userTF])) {
        return;
    }

    if(_keyboardIsShow)
    {
        [_userTF resignFirstResponder];
        [_passwordTF resignFirstResponder];
        [_verifycodeTF resignFirstResponder];
    }
}

-(void)viewDidLayoutSubviews
{
    CGFloat rate = 1.0f;
    if(HARDWARE_SCREEN_HEIGHT >= 736)
    {
        rate = 1.30f;
    }
    [_scrollView setContentSize:CGSizeMake(self.view.frame.size.width, 620*rate)];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear: animated];
     self.isShowError = YES;
    self.navigationController.navigationBarHidden = YES;
    [self addKeyBoardAction];
    
    CAccountModel *curAcc = [[CFolderMgr shareInstance].accMgr getRecentlyLoginAccount];
    [self updateUserList];
    [_tb reloadData];

    if(curAcc)
    {
        _userTF.text = curAcc.loginName;
        //        _passwordTF.text = self.account.passWord;
        [_logoView sd_setImageWithURL:[NSURL URLWithString:[[CXmppRequestMgr shareInstance] DownHeadFileWithContact:curAcc.userId]] placeholderImage:[UIImage imageNamed:@"defaultHeaderImage"]];
        
        
    }

}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.isShowError = NO;
    [self removeKeyBoardAction];
}

-(void)addKeyBoardAction
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(loginkeyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardShow:)
                                                 name:UIKeyboardDidShowNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardHide:)
                                                 name:UIKeyboardDidHideNotification
                                               object:nil];
    
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginError:) name:K_XMPPLOGINERRMSG object:nil];
}


-(void)removeKeyBoardAction
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidHideNotification object:nil];
}
//- (void)loginError:(NSNotification *)notif
//{
//    NSLog(@"%@niotif===============",notif);
//}
//
-(void)loginResult:(NSNotification *)notif
{
//    NSLog(@"notif:%@", notif);
    BOOL isForceQuit = [USER_DEFAULT boolForKey:ISFORCEQUIT];
    NSDictionary *dic = (NSDictionary *)notif.object;
    NSNumber *resultObj = (NSNumber *)[dic objectForKey:K_XMPPLOGINSTATUS];
    if([resultObj boolValue])
    {
        if([USER_DEFAULT boolForKey:is_GuseturePassword] && !isForceQuit&&[[CXmppMgr shareInstance].xmppStream isAuthenticated])
        {
            GesturePasswordController *passwordVC = [[GesturePasswordController alloc] init];
            [self presentViewController:passwordVC animated:YES completion:nil];
        }
        //bug 6296 fixed by 荣则兵
        [USER_DEFAULT setBool:NO forKey:ISFORCEQUIT];
        [USER_DEFAULT synchronize];
        if (_passwordTF.text.length > 0 && _userTF.text.length > 0) {
            
            NSString *userName = [_userTF.text stringByReplacingOccurrencesOfString:@"@" withString:@"_"];
            NSString *loginName = [_userTF.text lowercaseString];
            NSString *password = _passwordTF.text;
            _userTF.text = @"";
            _passwordTF.text = @"";
            [[CFolderMgr shareInstance].accMgr updateAllAcountStatus];
            CAccountModel *account = [[CFolderMgr shareInstance].accMgr getAccountByUserName:[userName lowercaseString]];
            if (account) {
                account.userName = [userName lowercaseString];
                account.loginName = loginName;
                account.passWord = password;
                account.isShowInList = YES;
                account.recentlyLogin = YES;
    
                [[CFolderMgr shareInstance].accMgr updateAccount:account];
                
            } else {
                account = [[CAccountModel alloc] init];
                account.userName = [userName lowercaseString];
                account.loginName = loginName;
                account.passWord = password;
                account.isShowInList = YES;
                account.recentlyLogin = YES;
                [[CFolderMgr shareInstance].accMgr insetAccount:account];
            }

            [[FMShareDataBase shareDataBase] updatePersonalQueue];
            PersonalVersion *persionVersionUpdate = [[PersonalVersion alloc] init];
            [persionVersionUpdate updateDBVersions:account.userName];
            
            
            if ([APPTOKEN isEqualToString:@"eFeng"]) {
                EFRootViewController *eFeng = [[EFRootViewController alloc] init];
                [self.navigationController pushViewController:eFeng animated:NO];
            } else if ([APPTOKEN isEqualToString:@"eTong"]){
                WZRootViewController *root = [[WZRootViewController alloc] init];
                [self.navigationController pushViewController:root animated:NO];
            } else if ([APPTOKEN isEqualToString:@"eFengAndEtong"]) {
                EFengAndEtongRootController *efengAndEtong = [[EFengAndEtongRootController alloc] init];
                [self.navigationController pushViewController:efengAndEtong animated:NO];
            } else {
                EFRootViewController *eFeng = [[EFRootViewController alloc] init];
                [self.navigationController pushViewController:eFeng animated:NO];
            }
            
        } else {
        
            
        }
       
        
        [self loaddata];

    }
    else
    {
        if (self.isShowError) {
            NSString *error = [dic objectForKey:K_XMPPLOGINERRMSG];
//            当前网络连接异常,请检查
            if (![error isEqualToString:@"服务器异常!"]) {
                NSString *newErr = nil;
                if ([error isEqualToString:@"用户名或密码错误!"]) {
                    newErr = @"用户名或密码错误!";
                } else if ([error isEqualToString:@"网络错误!"]) {
                    newErr = @"当前网络连接异常,请检查";
                } else {
                    newErr = @"与服务器断开连接";
                }
                
                [self setErrStatus:YES errorMsg:error];
                _passwordTF.text = @"";
                _errTimes++;
                if(_errTimes >= KVERIFYTIMES)
                {
                    [self setverifyStatus:YES];
                    [self updateVerifyCode];
                }
            }
      
      }
    }
    [UIUtil hideMBProgressViewForView:self.view];
}

- (void)loaddata
{
    
    CContactMgr *contactMgr = [[CContactMgr alloc] init];
    BOOL iscontact = [contactMgr loadAllContact];
    
    if (!iscontact) {
        [[CXmppRequestMgr shareInstance] getDeptUserTree];
        
    } else{
        
        [[CXmppRequestMgr shareInstance] getDelAndDisableUserWithSuccessHandel:^(AFHTTPRequestOperation *operation, id responseObject) {
        
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                
            if ([responseObject isKindOfClass:[NSArray class]]) {
                [contactMgr delAllDelContact];
                NSMutableArray *contArray = [NSMutableArray array];
                [responseObject enumerateObjectsUsingBlock:^(NSDictionary *index, NSUInteger idx, BOOL *stop) {
                    CContactModel *contactModel = [[CContactModel alloc] init];
                    contactModel.Position = [index objectForKey:@"position"];
                    contactModel.EXtenSion = [index objectForKey:@"extension"];
                    contactModel.UserID = [index objectForKey:@"id"];
                    contactModel.isDel = [[index objectForKey:@"isDel"] boolValue];
                    contactModel.Autograph = [index objectForKey:@"autograph"];
                    contactModel.UserCode = [index objectForKey:@"userCode"];
                    contactModel.UserName = [index objectForKey:@"realName"];
                    contactModel.DEPTID = [index objectForKey:@"deptId"];
                    contactModel.RoleID = [index objectForKey:@"roleId"];
                    contactModel.SEX = [index objectForKey:@"sex"];
                    contactModel.MobileTelephone = [index objectForKey:@"mobilePhone"];
                    contactModel.Email = [index objectForKey:@"email"];
                    contactModel.birthDay = [index objectForKey:@"birthday"];
                    contactModel.address = [index objectForKey:@"address"];
                    contactModel.Telephone = [index objectForKey:@"telephone"];
                    contactModel.HeadPortrait = [index objectForKey:@"HeadPortrait"];
                    contactModel.DEPNAME = [index objectForKey:@"dept"];
                    contactModel.PinYin = [[[NSString pinyinWithHanzi:contactModel.UserName] lowercaseString] stringByReplacingOccurrencesOfString:@" " withString:@""];
                    contactModel.firstLetter = [[NSString namToPinYinFisrtNameWith:[index objectForKey:@"realName"]] lowercaseString];
                    contactModel.compCode = [NSString stringWithFormat:@"%@",[index objectForKey:@"compCode"]];
                    contactModel.IsAvailable = @"离线";
                    [contArray addObject:contactModel];
                    contactModel = nil;
                    
                }];
                [contactMgr batchInsertContact:contArray];
            }
                });
        } filarueHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        }];
       
        
        
        CContactModel *curModel = [contactMgr loadCurContact];
        CAccountModel *curAcc = [[CFolderMgr shareInstance].accMgr getRecentlyLoginAccount];
        curAcc.userId = curModel.UserID;
        [[CFolderMgr shareInstance].accMgr updateAccount:curAcc];
        [[CXmppRequestMgr shareInstance] loadShareData];
        [[CXmppRequestMgr shareInstance] getGroupListWithUserId:curModel.UserID];
        [[CXmppRequestMgr shareInstance] getMineAttentionWithsuccessHandel:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSString *result = responseObject[@"result"];
            
            if ([result isEqualToString:@"success"]) {
                
                CAttentionMgr *attenMgr = [[CAttentionMgr alloc] init];
                [attenMgr delAllAttentionContacts];
                
                NSMutableArray *arrayM = [NSMutableArray array];
                NSString *meAttentionId = responseObject[@"meAttentionId"];
                NSArray *meAttentionIdArray = [meAttentionId componentsSeparatedByString:@","];
                [meAttentionIdArray enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL *stop) {
                    CMineAttentionContact *attention = [[CMineAttentionContact alloc] init];
                    attention.userId = obj;
                    attention.isAttentionMe = NO;
                    [arrayM addObject:attention];
                }];
                
                NSString *attentionMeId = responseObject[@"attentionMeId"];
                NSArray *attentionMeIdArray = [attentionMeId componentsSeparatedByString:@","];
                [attentionMeIdArray enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL *stop) {
                    CMineAttentionContact *attention = [[CMineAttentionContact alloc] init];
                    attention.userId = obj;
                    attention.isAttentionMe = YES;
                    [arrayM addObject:attention];
                }];
                [attenMgr batchInsertAttentionContact:arrayM];
            } else {
                
            }
            
        } filarueHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
            
        }];

        [[CXmppRequestMgr shareInstance] getKefuList];
        [[CXmppRequestMgr shareInstance] getOftenContact];
        [[CXmppRequestMgr shareInstance] getOtherUserUpdateInfo:curModel.UserID];
        [[CXmppRequestMgr shareInstance] getUpdateInfo];
        [[CXmppRequestMgr shareInstance] getUserSettingInfo];
        [[CXmppRequestMgr shareInstance] getCallCenterTelePhoneNumberWithUserId:curModel.UserID];
        
    }
    
}



- (void)loginkeyboardWillShow:(NSNotification *)notif {

    
    CGRect rect = [[notif.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
//    CGFloat y = rect.origin.y;
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.25];
//    NSArray *subviews = [self subviews];
//    for (UIView *sub in subviews) {
//        
//        CGFloat maxY = CGRectGetMaxY(sub.frame);
//        if (maxY > y - 2) {
//            sub.center = CGPointMake(CGRectGetWidth(self.frame)/2.0, sub.center.y - maxY + y - 2);
//        }
//    }
    if (rect.origin.y >= CGRectGetMaxY(_errIconImageView.frame)) {
        
    } else {
        [_scrollView setContentOffset:CGPointMake(0, CGRectGetMaxY(_errIconImageView.frame) - rect.origin.y) animated:NO];
    }
    [UIView commitAnimations];
    _keyboardIsShow = YES;
}

- (void)keyboardShow:(NSNotification *)notif {
//    NSLog(@"%@",notif);
    _keyboardIsShow = YES;
}

- (void)keyboardWillHide:(NSNotification *)notif {

    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.25];
//    NSArray *subviews = [self subviews];
//    for (UIView *sub in subviews) {
//        if (sub.center.y < CGRectGetHeight(self.frame)/2.0) {
//            sub.center = CGPointMake(CGRectGetWidth(self.frame)/2.0, CGRectGetHeight(self.frame)/2.0);
//        }
//    }
    [_scrollView setContentOffset:CGPointMake(0, 0) animated:NO];
    [UIView commitAnimations];
    _keyboardIsShow = NO;
}

- (void)keyboardHide:(NSNotification *)notif {
    _keyboardIsShow = NO;
}


- (NSString *)createRandomStr
{
    
    //用了大写字母,自己感觉要比小写好点吧，方法比较笨，嘿嘿
    NSArray *changeArray = [[NSArray alloc] initWithObjects:@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",
                    @"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z",nil] ;
    
    NSMutableString *getStr = [[NSMutableString alloc] initWithCapacity:5] ; //可变字符串，存取得到的随机数
    
    NSMutableString *changeString = [[NSMutableString alloc] initWithCapacity:6] ; //可变string，最终想要的验证码
    for(NSInteger i = 0; i < 4; i++) //得到四个随机字符，取四次，可自己设长度
    {
        NSInteger index = arc4random() % ([changeArray count] - 1);  //得到数组中随机数的下标
        getStr = [changeArray objectAtIndex:index];  //得到数组中随机数，赋给getStr
        
        changeString = (NSMutableString *)[changeString stringByAppendingString:getStr]; ///把随机字符加到可变string后面，循环四次后取完
    }
    
    return [changeString lowercaseString];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)loginAction:(UIButton *)button
{
    [self.view endEditing:YES];
    
    [self setErrStatus:NO errorMsg:nil];
    
    if(![self isCheckUserInfoValid])
    {
        return ;
    }
    else if(![UIUtil isNetworkReachable])
    {
        [self setErrStatus:YES errorMsg:@"当前网络连接异常,请检查"];
        return;
    }

//    __block NSString *imIp = @"efeng.wanzhao.com";
//    __block NSString *imIp = @"192.168.1.46";
    __block NSString *imIp = IMIP;
    __block NSInteger imPort = IMPORT;
//    CServerSettingModel *ser = [[[CServerSettingMgr alloc] init] getSetting];
//    if (ser.IMIp.length > 0) {
//        imIp = ser.IMIp;
//    }
//    if (ser.IMPort > 0) {
//        imPort = ser.IMPort;
//    }
    NSString *userName = [[_userTF.text stringByReplacingOccurrencesOfString:@"@" withString:@"_"] lowercaseString];
    NSString *password = _passwordTF.text;
//    if (password.length<6) {
//        [self setErrStatus:YES errorMsg:@"密码不能小于6位数"];
//        return;
//    }

    [UIUtil addMBProgressViewTitle:@"正在登录..." inView:self.view alpha:0.5 failureTitle:@"当前网络不可用，请检查网络"];
    NSString *requesUrlstring = [NSString stringWithFormat:@"http://%@:%zd/imconsole/general_getServerStatus.action?userName=%@",imIp, imPort, userName];
    NSString *requesUrl = [requesUrlstring stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer];
    NSMutableURLRequest *request = [serializer requestWithMethod:@"GET" URLString:requesUrl parameters:nil error:nil];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    operation.responseSerializer = [AFJSONResponseSerializer serializer];
    operation.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/json"];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = (NSDictionary *)responseObject;
        NSString *openFireIP = [dic objectForKey:@"openfireIP"];
        NSString *openFirePort = [dic objectForKey:@"openfirePort"];
        CServerSettingMgr *serverMgr = [[CServerSettingMgr alloc] init];
        [serverMgr deleServerSetting];
        CServerSettingModel *serverSetting = [[CServerSettingModel alloc] init];
        serverSetting.IMIp = imIp;
        NSString *idkey = [dic stringForKey:@"idkey"];
        if (M_ISSTRNULL(idkey)) {
                idkey = @"111111";
            }
            serverSetting.yuLiuZiduan1 = idkey;
            //        NSLog(@"%@",dic);
            serverSetting.IMPort = imPort;
            serverSetting.OpenFireIP = openFireIP;
            serverSetting.OpenFirePort = openFirePort.integerValue;
            serverSetting.companyId = [NSString stringWithFormat:@"%@",[dic objectForKey:@"companyId"]];
            serverSetting.companyName = [NSString stringWithFormat:@"%@",[dic objectForKey:@"companyName"]];
            serverSetting.companyStatus = [NSString stringWithFormat:@"%@",[dic objectForKey:@"companyStatus"]];
            [serverMgr insetServerSetting:serverSetting];
            [[FMShareDataBase shareDataBase] updateCompanyQueue];
            CommonVersion *versionUpdate = [[CommonVersion alloc] init];
            [versionUpdate updateCompanyDBVersions];
            CXmppMgr *xmppMgr = [CXmppMgr shareInstance];
        if ([serverSetting.companyStatus isEqualToString:@"yes"]) {
            [xmppMgr disconnect];
            [xmppMgr connect:userName password:password serverIp:serverSetting.OpenFireIP serverPort:serverSetting.OpenFirePort];
        }
        else
        {
            if ([serverSetting.companyStatus isEqualToString:@"accountDisable"])
            {
                [self setErrStatus:YES errorMsg:@"此账号已被停用!"];
            }
            if ([serverSetting.companyStatus isEqualToString:@"no"])
            {
                [self setErrStatus:YES errorMsg:@"e蜂通信已被停用!"];
            }
            if ([serverSetting.companyStatus isEqualToString:@"accountNotExist"])
            {
                [self setErrStatus:YES errorMsg:@"用户名密码错误！"];
            }
            if ([serverSetting.companyStatus isEqualToString:@"companyNotExist"])
            {
                [self setErrStatus:YES errorMsg:@"用户名密码错误！"];
            }

            [UIUtil hideMBProgressViewForView:self.view];
            
        }
            
        
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [UIUtil hideMBProgressViewForView:self.view];
        [self setErrStatus:YES errorMsg:@"当前网络连接异常,请检查"];
        return;
    }];
    [_queen addOperation:operation];
    
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
        if (buttonIndex) {
            
        }else if([[[UIDevice currentDevice] systemVersion] floatValue] >8.0){
            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if ([[UIApplication sharedApplication] canOpenURL:url]) {
                [[UIApplication sharedApplication] openURL:url];
            }
            }
    
}

-(BOOL)isCheckUserInfoValid
{

    NSString *userName = _userTF.text;
    NSString *password = _passwordTF.text;
    NSString *inputVerifyCode  = [_verifycodeTF.text lowercaseString];
    BOOL ret = YES;
    if(M_ISSTRNULL(userName))
    {
        [self setErrStatus:YES errorMsg:@"请输入用户名"];
        ret = NO;
    }
    else if(M_ISSTRNULL(password))
    {
        [self setErrStatus:YES errorMsg:@"请输入密码"];
        ret = NO;
    }
    else if(isUseverifyCode)
    {
        if(M_ISSTRNULL(inputVerifyCode))
        {
            [self setErrStatus:YES errorMsg:@"请输入验证码"];
            [self updateVerifyCode];
            ret = NO;
        }
        else if(![inputVerifyCode isEqualToString:self.verifyCode])
        {
            [self setErrStatus:YES errorMsg:@"验证码输入错误"];
            [self updateVerifyCode];
            ret = NO;
        }
    }
    return ret;
}



-(void)setverifyStatus:(BOOL)isShow
{
    if (isShow == NO) {
        
        CGRect rec = _loginBtn.frame;
        rec.origin.y = CGRectGetMaxY(self.passwordBackView.frame) + 30.0f;
        _loginBtn.frame = rec;
        _errIconImageView.frame = CGRectMake(15.0f, CGRectGetMaxY(_loginBtn.frame) + 17.5f, _errIconImageView.image.size.width, _errIconImageView.image.size.height);
        _errMsgLabel.frame = CGRectMake(CGRectGetMaxX(_errIconImageView.frame) + 6.0f, CGRectGetMaxY(_loginBtn.frame) + 17.5f,  159.0f, _errIconImageView.image.size.height);
        _settingNet.frame = CGRectMake(CGRectGetMaxX(_errMsgLabel.frame), CGRectGetMaxY(_loginBtn.frame) + 17.5f, 60.0f, _errIconImageView.image.size.height);

    }
    [_verifyLabel setHidden:!isShow];
    [_verifycodeTF setHidden:!isShow];
    [_verifyRefreshBtn setHidden:!isShow];
    _isUseverifyCode = isShow;
}

-(void)updateVerifyCode
{
    self.verifyCode = [self createRandomStr];
    _verifyLabel.text = self.verifyCode ;
    _verifycodeTF.text = @"";
    isUseverifyCode = YES;
    CGRect rec = _loginBtn.frame;
    rec.origin.y = CGRectGetMaxY(self.passwordBackView.frame) + 60.0f;
    _loginBtn.frame = rec;
    
    
     _errIconImageView.frame = CGRectMake(15.0f, CGRectGetMaxY(_loginBtn.frame) + 17.5f, _errIconImageView.image.size.width, _errIconImageView.image.size.height);
     _errMsgLabel.frame = CGRectMake(CGRectGetMaxX(_errIconImageView.frame) + 6.0f, CGRectGetMaxY(_loginBtn.frame) + 17.5f,  159.0f, _errIconImageView.image.size.height);
    _settingNet.frame = CGRectMake(CGRectGetMaxX(_errMsgLabel.frame), CGRectGetMaxY(_loginBtn.frame) + 17.5f, 60.0f, _errIconImageView.image.size.height);
}

-(void)setErrStatus:(BOOL)status errorMsg:(NSString *)errorMsg
{
    
    if(status)
    {
        if ([errorMsg isEqualToString:@"当前网络连接异常,请检查"]) {
            [_settingNet setHidden:NO];
        }else{
            [_settingNet setHidden:YES];
            
        }
        [_errIconImageView setHidden:NO];
        [_errMsgLabel setHidden:NO];
        [_errMsgLabel setText:errorMsg];
    }
    else
    {
        [_settingNet setHidden:YES];
        [_errIconImageView setHidden:YES];
        [_errMsgLabel setHidden:YES];
        
    }
}


- (IBAction)changeOpenStatus:(id)sender {
    [self updateUserList];
    if (isOpened) {
        [UIView animateWithDuration:0.3 animations:^{
            UIImage *closeImage=[UIImage imageNamed:@"userNameListImg"];
            [_historyUser setImage:closeImage forState:UIControlStateNormal];
            
            CGRect frame=_tb.frame;
            
            frame.size.height=0;
            [_tb setFrame:frame];
            
        } completion:^(BOOL finished){
            
            isOpened=NO;
        }];
    }else{

        __block float tbHeight;
//        if (_userList.count >= 2) {
//            tbHeight = 88.0f;
//        } else {
//            tbHeight = _userList.count * 44.0f;
//        }
        tbHeight = _userList.count * 44.0f;
        if (_userList.count>5) {
            tbHeight = 5 * 44.0f;

        }
        [UIView animateWithDuration:0.3 animations:^{
            UIImage *openImage=[UIImage imageNamed:@"userNameListImg"];
            [_historyUser setImage:openImage forState:UIControlStateNormal];
            
            CGRect frame=_tb.frame;
            
            frame.size.height=tbHeight;
            [_tb setFrame:frame];
        } completion:^(BOOL finished){
            
            isOpened=YES;
        }];
        
        
    }
    
}


- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    CAccountModel *curAcc = [[CFolderMgr shareInstance].accMgr getAccountByUserName:[[_userTF.text stringByReplacingOccurrencesOfString:@"@" withString:@"_"] lowercaseString]];
    if (textField == _userTF) {
        
        [_logoView sd_setImageWithURL:[NSURL URLWithString:[[CXmppRequestMgr shareInstance] DownHeadFileWithContact:curAcc.userId]] placeholderImage:[UIImage imageNamed:@"defaultHeaderImage"]];
    }
    return YES;
}




//- (void)uploadFinished:(ASIHTTPRequest *)theRequest
//{
////    [resultView setText:[NSString stringWithFormat:@"Finished uploading %llu bytes of data",[theRequest postLength]]];
//    
//#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0
//    // Clear out the old notification before scheduling a new one.
//    if ([[[UIApplication sharedApplication] scheduledLocalNotifications] count] > 0)
//        [[UIApplication sharedApplication] cancelAllLocalNotifications];
//    
//    // Create a new notification
//    UILocalNotification *notification = [[UILocalNotification alloc] init];
//    if (notification) {
//        [notification setFireDate:[NSDate date]];
//        [notification setTimeZone:[NSTimeZone defaultTimeZone]];
//        [notification setRepeatInterval:0];
//        [notification setSoundName:@"alarmsound.caf"];
//        [notification setAlertBody:@"Boom!\r\n\r\nUpload is finished!"];
//        [[UIApplication sharedApplication] scheduleLocalNotification:notification];
//    }
//#endif
//}







#pragma mark --
#pragma mark UITextFieldDelegate
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if (isOpened) {
        [UIView animateWithDuration:0.3 animations:^{
            UIImage *closeImage=[UIImage imageNamed:@"userNameListImg"];
            [_historyUser setImage:closeImage forState:UIControlStateNormal];
            
            CGRect frame=_tb.frame;
            
            frame.size.height=0;
            [_tb setFrame:frame];
            
        } completion:^(BOOL finished){
            
            isOpened=NO;
        }];
    }
    return YES;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string   // return NO to not change text
{
    
    if ([string isEqualToString:@"\n"]) {
        [textField resignFirstResponder];
    }
    if(!M_ISSTRNULL(string))
    {
        
        NSInteger maxLen = 0;
        switch (textField.tag) {
            case KUSERNAMETAG:
                maxLen = 50;
//                bug6009 yh
                _passwordTF.text = @"";
                break;
            case KPASSWORDTAG:
                maxLen = 12;
                break;
            case KverifyCODETAG:
                maxLen = 4;
                break;
                
            default:
                break;
        }
        
        if([textField.text length] >= maxLen)
        {
            return NO;
        }
    }
    
    return YES;
}

//- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
//{
//    if (textField == _userTF) {
//        [_logoView sd_setImageWithURL:[NSURL URLWithString:[[CXmppRequestMgr shareInstance] DownHeadFileWithContact:model.userId]] placeholderImage:[UIImage imageNamed:@"defaultHeaderImage"]];
//
//    }
//    
//    return YES;
//}

//- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
//{
//    
//}
#pragma mark --
#pragma mark SectionDel_Delegate
-(void)delItem:(NSString *)delName
{
    _passwordTF.text = @"";
    if(M_ISSTRNULL(delName))
    {
        return;
    }
    
    CAccountModel *account = [[CFolderMgr shareInstance].accMgr getAccountByUserName:delName];
    if(account != nil)
    {
        account.isShowInList = NO;
        [[CFolderMgr shareInstance].accMgr updateAccount:account];
        _userList = [[CFolderMgr shareInstance].accMgr getAccountNameList];
        float tbHeight = 0;
        if (_userList.count >1) {
            tbHeight = _userList.count * 44.0f;
        }
        if (_userList.count >5) {
            tbHeight = 5 * 44.0f;

        }
        
        CGRect frame= _tb.frame;
        
        frame.size.height=tbHeight;
        [_tb setFrame:frame];
        
        
        [_tb reloadData];
        
    }
}

- (void)clickSetting{
    
    NSURL *url = [NSURL URLWithString:@"prefs:root=General"];
    if ([[UIApplication sharedApplication] canOpenURL:url]) {
        [[UIApplication sharedApplication] openURL:url];
    }
    
    
}

@end
